package ru.example.mongotest2.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.example.mongotest2.domain.Person;
import ru.example.mongotest2.service.PersonService;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/persons")
@RestController
@RequiredArgsConstructor
public class PersonController {

    private final PersonService personService;

    @GetMapping("/{id}")
    public ResponseEntity<Person> getById(@PathVariable String id) {
        return personService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/all")
    public ResponseEntity<List<Person>> getAll() {
        return ResponseEntity.ok(new ArrayList<>(personService.getAll()));
    }

    @GetMapping
    public ResponseEntity<List<Person>> findByAge(@RequestParam(name = "age", required = false) int age) {
        return ResponseEntity.ok(new ArrayList<>(personService.findByAge(age)));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable String id) {
        personService.delete(id);
        return ResponseEntity.noContent().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Person> update(@PathVariable String id,
                                         @RequestBody Person person) {
        person.setId(id);
        return ResponseEntity.ok(personService.update(person));
    }

    @PostMapping
    public void create(@RequestBody Person person) {
        personService.create(person);
    }

}
